#include "dirStack.h"

dirNode_t* createNewNode(char* commandName){
    dirNode_t* newNode = (dirNode_t*)calloc(1,sizeof(dirNode_t));
    int length = strlen(commandName);
    char* c = (char*)calloc(length+1,sizeof(char));
    strcpy(c,commandName);
    newNode->cname = c;
    
    return newNode;
}

dirStack_t* initDirStack(){
    dirStack_t* dstack = (dirStack_t*)calloc(1,sizeof(dirStack_t));

    return dstack;
}

int destoryDirStack(dirStack_t* dstack){
    dirNode_t* currentnode = dstack->top;
    
    while(currentnode != NULL){
        dirNode_t* temp = currentnode;
        currentnode = currentnode->next;
        free(temp->cname);
        free(temp);
    }
    dstack->top = NULL;
    dstack->bottom = NULL;
    return 0;
}

int pushDirStack(dirStack_t* dstack,char* cname){
    dirNode_t* newNode = createNewNode(cname);
    if(dstack->bottom ==NULL){
        dstack->top = newNode;
        dstack->top->next = dstack->bottom;
        dstack->bottom = newNode;
    }
    else{
        newNode->next = dstack->top;
        dstack->top = newNode;
    }
    dstack->stackElement++;
    return 0;
}

int popDirStack(dirStack_t* dstack,char* cname){
    dirNode_t* outNode;
    if(dstack->stackElement == 0){
        return -1;
    }
    else if(dstack->stackElement == 1){
        outNode = dstack->top;
        dstack->top = NULL;
        dstack->bottom = NULL;
        cname = outNode->cname;
    }
    else{
        outNode = dstack->top;
        dstack->top = dstack->top->next;
        cname = outNode->cname;
    }
    free(outNode);
    dstack->stackElement--;
    return 0;
}
void print_dirstack(dirStack_t* dstack){
    printf("now stack struct is : \n");
    dirNode_t* currentnode = dstack->top;
    while(currentnode!=NULL){
        printf("%s",currentnode->cname);
        if(currentnode->next != NULL){
            printf("--->");
        }
        currentnode = currentnode->next;
    }
    printf("\n");
}

/* int main(){ */
    
/*     char p[] = "dir"; */
/*     char p2[] = ".."; */
/*     char p3[] = "."; */
/*     char p4[] = "filename"; */

/*     dirStack_t* dstack = initDirStack(); */
/*     pushDirStack(dstack,p); */
/*     print_dirstack(dstack); */
/*     pushDirStack(dstack,p2); */
/*     print_dirstack(dstack); */
/*     pushDirStack(dstack,p3); */
/*     print_dirstack(dstack); */
/*     pushDirStack(dstack,p4); */
/*     print_dirstack(dstack); */

/*     char* outcommand = NULL; */
/*     popDirStack(dstack,outcommand); */
/*     print_dirstack(dstack); */
/*     popDirStack(dstack,outcommand); */
/*     print_dirstack(dstack); */
/*     popDirStack(dstack,outcommand); */
/*     print_dirstack(dstack); */
/*     popDirStack(dstack,outcommand); */
/*     print_dirstack(dstack); */
    

/*     return 0; */
/* } */












